package com.supreme.commontools;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;

public class DateTimeUtils {

    /**
     * 基本日期格式模板
     */
    public static final String D_TPL = "yyyy-MM-dd";

    /**
     * 基本时间格式模板
     */
    public static final String T_TPL = "HH:mm:ss";

    /**
     * 基本DATE格式模板
     */
    public static final String DT_TPL = "yyyy-MM-dd HH:mm:ss";

    /**
     * UTC时间格式模板
     */
    public static final String UTC_DT_TPL = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    /**
     * Date 转 LocalDateTime
     * @param date date
     * @return localDateTime
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        return date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
    }

    /**
     * LocalDateTime 转 Date
     * @param localDateTime localDateTime
     * @return date
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    public static String localDateTimeFormat() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(DT_TPL));
    }

    /**
     * UTC 时间转 本地时间格式字符串
     * @param utcDateTime utcDateTime
     * @return 常规时间格式字符串
     */
    public static String utcToLocalDateTimeString(String utcDateTime) {
        Instant instant = LocalDateTime.parse(utcDateTime, DateTimeFormatter.ofPattern(UTC_DT_TPL))
                .toInstant(ZoneOffset.UTC);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                .format(DateTimeFormatter.ofPattern(DT_TPL));
    }

    public static String utcToOffsetDateTimeString(String utcDateTime, int offset) {
        LocalDateTime localDateTime = LocalDateTime.parse(utcDateTime, DateTimeFormatter.ofPattern(UTC_DT_TPL));
        Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
        instant = instant.plus(offset, ChronoUnit.HOURS);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                .format(DateTimeFormatter.ofPattern(DT_TPL));
    }

    public static long[] parseDateToTimeRange(String value) {
        long[] startEndTimes = new long[2];

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(D_TPL, Locale.getDefault());
        LocalDate localDate = LocalDate.parse(value, dateTimeFormatter);

        LocalDateTime startDateTime = localDate.atStartOfDay();
        long startTime = startDateTime.toEpochSecond(ZoneOffset.of("+8"));
        startEndTimes[0] = startTime;

        LocalDateTime endDatetime = startDateTime.plusDays(1);
        long endTime = endDatetime.toEpochSecond(ZoneOffset.of("+8"));
        startEndTimes[1] = endTime - 1;

        return startEndTimes;
    }
}
